/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.wx.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.wx.dao.WxUserDao;
import com.thinkgem.jeesite.modules.wx.entity.WxUser;

import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;

/**
 * 微信会员Service
 * @author Real
 * @version 2017-05-19
 */
@Service
@Transactional(readOnly = true)
public class WxUserService extends CrudService<WxUserDao, WxUser> {
	
	@Autowired
	private WeixinService wxService;
	

	public WxUser get(String id) {
		return super.get(id);
	}
	
	public List<WxUser> findList(WxUser wxUser) {
		return super.findList(wxUser);
	}
	
	public Page<WxUser> findPage(Page<WxUser> page, WxUser wxUser) {
		return super.findPage(page, wxUser);
	}
	
	@Transactional(readOnly = false)
	public void save(WxUser wxUser) {
		super.save(wxUser);
	}
	
	@Transactional(readOnly = false)
	public void delete(WxUser wxUser) {
		super.delete(wxUser);
	}
	
	@Transactional(readOnly = false)
	public void getMpUser(String key) throws Exception{
		WxMpUserService wxMpUserService = wxService.getApi(key).getUserService();
		List<WxUser> wxUserList = new ArrayList<WxUser>();
			WxMpUserList  wxMpUserList = wxMpUserService.userList(null);
			while(wxMpUserList.getCount()>0){
				List<String> openIds = wxMpUserList.getOpenids();
				List<WxMpUser> wxMpUsers = wxMpUserService.userInfoList(openIds);
				for(WxMpUser wxMpUser:wxMpUsers){
					WxUser wxUser = new WxUser();
					wxUser.setCity(wxMpUser.getCity());
					wxUser.setProvince(wxMpUser.getProvince());
					wxUser.setCountry(wxMpUser.getCountry());
					wxUser.setHeadimgurl(wxMpUser.getHeadImgUrl());
					wxUser.setNickname(wxMpUser.getNickname());
					wxUser.setOpenid(wxMpUser.getOpenId());
					wxUser.setSex(wxMpUser.getSex());
					wxUser.setSexid(wxMpUser.getSexId());
					wxUser.setUnionid(wxMpUser.getUnionId());
					wxUser.setSubscribe(wxMpUser.getSubscribe());
					wxUser.setSubscribeat(wxMpUser.getSubscribeTime());
					wxUser.setWxid(key);
					wxUser.preInsert();
					wxUserList.add(wxUser);
				}
				String nextOpenId = wxMpUserList.getNextOpenid();
				wxMpUserList = wxMpUserService.userList(nextOpenId);
			}
			int count = this.dao.deleteByWxid(key);
			logger.info("批量删除用户数目为：" + count);
			count = this.dao.insertByBatch(wxUserList);
			logger.info("批量插入用户数目为：" + count);
	}
	
}